<template>
  <div class="single-image-upload">
    <el-upload
      class="uploader"
      ref="upload"
      :style="{ height: height, width: width }"
      :action="apiBaseUrl"
      :headers="{
        Authorization: $cookie.get('Authorization_vp'),
      }"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :limit="limit"
    >
      <img v-if="imageUrl" :src="resourcesUrl + imageUrl" class="" />
      <i v-else class="el-icon-plus uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        apiBaseUrl: process.env.VUE_APP_BASE_API + "/admin/file/upload/img/path",
        imageUrl: "",
      };
    },
    props: {
      modelValue: {
        type: String,
        default: "",
      },
      disabled: {
        default: false,
        type: Boolean,
      },
      limit: {
        default: 1,
        type: Number,
      },
      // 宽高
      width: {
        default: '200px',
        type: String,
      },
      height: {
        default: '200px',
        type: String,
      },
    },
    watch: {
      modelValue: function (val) {
        if (val) {
          this.imageUrl = val;
        }
      },
    },
    mounted() {
      if (this.modelValue) {
        this.imageUrl = this.modelValue;
      }
    },
    methods: {
      handleSuccess(res, file) {
        this.$refs.upload.clearFiles();
        this.imageUrl = res.data;
        this.$emit("input", res.data);
        this.$emit("update:modelValue", res.data);
      },
      beforeUpload(file) {
        const validImageTypes = ["image/png", "image/jpeg", "image/jpg"];
        const isImage = validImageTypes.includes(file.type);
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isImage) {
          this.$message.error("上传图片只能是 PNG、JPG 或 JPEG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 2MB!");
        }
        return isImage && isLt2M;
      },
    },
  };
</script>

<style lang="scss">
  .uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 100%;
    width: 100%;
    img{
      height: 100%;
      width: 100%;
    }
  }
  .uploader .el-upload:hover {
    border-color: #409eff;
  }
  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
